import {Component} from '@angular/core';
import {FormControl, FormGroup, NonNullableFormBuilder, Validators} from "@angular/forms";
import {Store} from "@ngrx/store";
import {ListActions} from "../store/actions/list.actions";
import {Router} from "@angular/router";
import {List} from "../store/model/list.model";

@Component({
  selector: 'app-add-info',
  templateUrl: './add-info.component.html',
  styleUrls: ['./add-info.component.less']
})
export class AddInfoComponent {
  constructor(
    private fb: NonNullableFormBuilder,
    private router: Router,
    private store: Store<{ list: { list: List[] } }>
  ) {
  }

  validateForm: FormGroup<{
    name: FormControl<string>;
    age: FormControl<number>;
  }> = this.fb.group({
    name: ['', [Validators.required]],
    age: [0, [Validators.required]],
  });

  submit(): void {
    if (this.validateForm.valid) {
      console.log('submit', this.validateForm.value);
      // this.store.dispatch(ListActions.addLists({
      //   data: {
      //     name: this.validateForm.value.name || '',
      //     age:this.validateForm.value.age || 0
      //   },
      // }))
      this.store.dispatch(ListActions.addEntity({
        data: {
          name: this.validateForm.value.name || '',
          age: this.validateForm.value.age || 0
        },
      }))
      this.router.navigateByUrl('/list')
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({onlySelf: true});
        }
      });
    }
  }

  back() {
    this.router.navigateByUrl('/list')
  }
}
